/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 *
 * @see You can view component api by: https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {SettingDrawer} from '@ant-design/pro-layout';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import {connect, history, Link, useIntl} from 'umi';
import {Button, Result, Spin} from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import {getMatchMenu} from '@umijs/route-utils';
import logo from '../assets/logo.svg';
import CommonFooter from "@/components/Footer/CommonFooter";
import {queryLoginAccountInfo} from "@/services/system";
import SmileOutlined from "@ant-design/icons/lib/icons/SmileOutlined";
import HeartOutlined from "@ant-design/icons/lib/icons/HeartOutlined";
import HomeOutlined from "@ant-design/icons/lib/icons/HomeOutlined";
import ShoppingOutlined from "@ant-design/icons/lib/icons/ShoppingOutlined";
import AccountBookOutlined from "@ant-design/icons/lib/icons/AccountBookOutlined";
import SettingOutlined from "@ant-design/icons/lib/icons/SettingOutlined";
import ToolOutlined from "@ant-design/icons/lib/icons/ToolOutlined";
import AuditOutlined from "@ant-design/icons/lib/icons/AuditOutlined";
import DatabaseOutlined from "@ant-design/icons/lib/icons/DatabaseOutlined";
import TeamOutlined from "@ant-design/icons/lib/icons/TeamOutlined";
import InsertRowAboveOutlined from "@ant-design/icons/lib/icons/InsertRowAboveOutlined";
import InsertRowBelowOutlined from "@ant-design/icons/lib/icons/InsertRowBelowOutlined";

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);

const IconMap = {
  home: <HomeOutlined />,
  purchase: <ShoppingOutlined />,
  material: <InsertRowAboveOutlined />,
  product: <InsertRowBelowOutlined />,
  customer: <TeamOutlined />,
  warehouse: <DatabaseOutlined />,
  order: <AuditOutlined />,
  process: <ToolOutlined />,
  finance: <AccountBookOutlined />,
  system: <SettingOutlined />,
  smile: <SmileOutlined />,
  heart: <HeartOutlined />,
  team: <TeamOutlined />,
};

const renderMenuTree = (menuList) => {
  const menuDataTemp = menuList.filter(item => {
    if (item.menuType === 1 && !item.menuPid) {
      item.path = item.url
      item.name = item.menuId
      item.icon = item.imageUrl && IconMap[item.imageUrl]
      item.children = [];
    }
    return item.menuType === 1 && !item.menuPid
  })
  menuList.filter(item => item.menuType === 1 && item.menuPid).forEach(item => {
    menuDataTemp.forEach(parent => {
      if (parent.menuId === item.menuPid) {
        item.path = item.url
        item.name = item.menuId
        item.icon = item.imageUrl && IconMap[item.imageUrl]
        parent.children.push(item);
      }
    })
  })
  return menuDataTemp
}

/** Use Authorized check all menu item */
const menuDataRender = (menuList) => {
  //console.log(('menuDataRender')
  //console.log((menuList)
  const oldMenuData = sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')).menuList : []
  //console.log((oldMenuData)
  if (oldMenuData.length === 0) {

  }

  return renderMenuTree(oldMenuData)
}


const defaultFooterDom = (
  <CommonFooter/>
);

const BasicLayout = (props) => {
  const [menuTreeData, setMenuTreeData] = useState([]);
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;
  const menuDataRef = useRef([]);
  useEffect(() => {
    // queryLoginAccountInfo().then(res => {
    //   if (res && res.status === '0') {
    //     const menuTreeTemp = renderMenuTree(res.data.menuList)
    //     setMenuTreeData(menuTreeTemp)
    //   }
    // })

    setMenuTreeData([{
      path: '/home',
      name: '概览',
      icon: <HomeOutlined />,
      children: [

      ],
    },{
      path: '/maintenance',
      name: '设备保养管理',
      icon: <ToolOutlined />,
      children: [
        {
          path: '/maintenance/maintenance-manage',
          name: '保养管理',
          icon: <SmileOutlined />
        },
        {
          path: '/maintenance/maintenance-history',
          name: '保养历史',
          icon: <SmileOutlined />,
        },
        {
          path: '/maintenance/equipment-manage',
          name: '设备管理',
          icon: <SmileOutlined />,
        }
      ],
    },{
      path: '/system',
      name: '系统管理',
      icon: <SettingOutlined />,
      children: [
        {
          path: '/system/department-manage',
          name: '部门管理',
          icon: <SmileOutlined />,
        },
        {
          path: '/system/account-manage',
          name: '用户管理',
          icon: <SmileOutlined />,
        },
        // {
        //   path: '/system/service-manage',
        //   name: '在线服务管理',
        //   icon: <SmileOutlined />,
        // }
      ],
    }
    ])
  }, []);

  useEffect(() => {
    // if (dispatch) {
    //   dispatch({
    //     type: 'user/fetchCurrent',
    //   });
    // }
  }, []);

  /** Init variables */

  const handleMenuCollapse = (payload) => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );
  const {formatMessage} = useIntl();
  return (
    <>
      {
        menuTreeData.length > 0 ? <ProLayout
          logo={logo}
          formatMessage={formatMessage}
          {...props}
          {...settings}
          onCollapse={handleMenuCollapse}
          onMenuHeaderClick={() => history.push('/home')}
          menuItemRender={(menuItemProps, defaultDom) => {
            if (
              menuItemProps.isUrl ||
              !menuItemProps.path ||
              location.pathname === menuItemProps.path
            ) {
              return defaultDom;
            }

            return <Link to={menuItemProps.path}>{defaultDom}</Link>;
          }}
          breadcrumbRender={(routers = []) => [
            {
              path: '/home',
              breadcrumbName: formatMessage({
                id: 'menu.home',
              }),
            },
            ...routers,
          ]}
          itemRender={(route, params, routes, paths) => {
            const first = routes.indexOf(route) === 0;
            return first ? (
              <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
            ) : (
              <span>{route.breadcrumbName}</span>
            );
          }}
          footerRender={() => {
            if (settings.footerRender || settings.footerRender === undefined) {
              return defaultFooterDom;
            }

            return null;
          }}
          menuDataRender={() => {
            return menuTreeData
          }}
          rightContentRender={() => <RightContent/>}
          postMenuData={(menuData) => {
            menuDataRef.current = menuData || [];
            return menuData || [];
          }}
        >
          <Authorized authority={authorized.authority} noMatch={noMatch}>
            {children}
          </Authorized>
        </ProLayout> : <Spin/>
      }
      {/*<SettingDrawer*/}
      {/*  settings={settings}*/}
      {/*  onSettingChange={(config) =>*/}
      {/*    dispatch({*/}
      {/*      type: 'settings/changeSetting',*/}
      {/*      payload: config,*/}
      {/*    })*/}
      {/*  }*/}
      {/*/>*/}
    </>
  );
};

export default connect(({global, settings}) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
